<template>
    <h1 style="margin: 0px 0px 0px 80px;">分类管理</h1>
  <div class="tree-wrapper">
    
    <!-- 数据为空提示 -->
    <div v-if="treeData.length === 0" class="empty">暂无分类数据</div>
    

    <!-- 树形结构 -->
    <ul class="category-tree" v-else>
      <!-- 渲染一级分类 -->
      <li v-for="(firstLevel, firstIndex) in treeData" :key="firstLevel.id" class="tree-item level-1">
        <div class="tree-item-content">
          <!-- 展开/折叠箭头 -->
          <span 
            class="toggle-icon" 
            @click.stop="toggleFirstLevel(firstIndex)"
            v-if="firstLevel.children.length > 0"
          >
            {{ firstLevel.expanded ? '▼' : '->' }}
          </span>
          
          <!-- 分类名称 -->
          <span class="category-name" @click="toggleFirstLevel(firstIndex)">
            {{ firstLevel.name }}
          </span>
          
          <!-- 操作按钮 -->
          <div class="action-buttons">
            <button class="add-btn" @click.stop="openEditModal(firstLevel)">
              编辑
            </button>
            <button class="add-btn" @click.stop="openAddModal(firstLevel)">
              添加子分类
            </button>
            <button class="delete-btn" @click.stop="deleteNode(null, firstIndex)">
              删除
            </button>
          </div>
        </div>
        
        <!-- 二级分类 -->
        <ul class="category-tree level-2" v-if="firstLevel.expanded">
          <li v-for="(secondLevel, secondIndex) in firstLevel.children" :key="secondLevel.id" class="tree-item">
            <div class="tree-item-content">
              <span 
                class="toggle-icon" 
                @click.stop="toggleSecondLevel(firstLevel, secondIndex)"
                v-if="secondLevel.children.length > 0"
              >
                {{ secondLevel.expanded ? '▼' : '->' }}
              </span>
              
              <span class="category-name" @click="toggleSecondLevel(firstLevel, secondIndex)">
                {{ secondLevel.name }}
              </span>
              
              <div class="action-buttons">
                <button class="add-btn" @click.stop="openEditModal(secondLevel)">
                  编辑
                </button>
                <button class="add-btn" @click.stop="openAddModal(secondLevel)">
                  添加子分类
                </button>
                <button class="delete-btn" @click.stop="deleteNode(firstLevel, secondIndex)">
                  删除
                </button>
              </div>
            </div>
            
            <!-- 三级分类 -->
            <ul class="category-tree level-3" v-if="secondLevel.expanded">
              <li v-for="(thirdLevel, thirdIndex) in secondLevel.children" :key="thirdLevel.id" class="tree-item">
                <div class="tree-item-content">
                  <span class="category-name">{{ thirdLevel.name }}</span>
                  
                  <div class="action-buttons">
                    <button class="add-btn" @click.stop="openEditModal(thirdLevel)">
                      编辑
                    </button>
                    <button class="add-btn" disabled >
                      添加子分类
                    </button>
                    <button class="delete-btn" @click.stop="deleteNode(secondLevel, thirdIndex)">
                      删除
                    </button>
                  </div>
                </div>
              </li>
            </ul>
          </li>
        </ul>
      </li>
        <button class="add-btn" style="float: right;" @click="openAddModal(null)">添加一级分类</button>
    </ul>
     <!-- 弹窗 -->
        <div class="modal-overlay" v-if="showModal">
            <div class="modal">
                <div class="modal-header">
                    <h2 class="modal-title">{{ isEditing ? '修改分类' : '添加分类' }}</h2>
                    <button  class="close-button" @click="closeModal">&times;</button><!-- 关闭弹窗 -->
                </div>
                
                <div class="form-group">
                    <label for="categoryName">分类名称</label>
                    <input 
                        type="text" 
                        id="categoryName" 
                        placeholder="请输入分类名称"
                        v-model="categoryName"
                        @blur="judgeCategoryName()"
                    >
                </div>
                <div class="error" >{{ error }}</div>
                <div class="modal-actions">
                    <button class="save-btn" @click="saveCategory">保存</button>
                    <button class="cancel-btn" @click="closeModal">取消</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';


const treeData = ref([]);
const loading = ref(false); // 添加加载状态

const showModal = ref(false);// 显示/隐藏弹窗
const categoryName = ref('');
const currentlyNode = ref([]); // 当前分类节点
const isEditing = ref(false);//判断是添加还是修改，false是添加
const error = ref('');// 错误信息

const getCategoryTree = async() => {
  loading.value = true; // 添加加载状态
  try {
    const response = await axios.get('/api/categoryTree');
    treeData.value = response.data.categoryTree;
    console.log('获取到的树形分类数据:', treeData.value);
    
  }catch(error) {
    console.error('获取数据失败:', error);
    treeData.value = [];
  } 
}

onMounted(() => {
  // 只在mounted时调用数据获取，数据获取后内部处理树形转换
  // getCategoryList();
  getCategoryTree();
});

// 打开添加分类弹窗
const openAddModal = (parent) => {
    currentlyNode.value = parent;
    isEditing.value = false;
    categoryName.value = '';
    showModal.value = true;
};

// 打开修改分类弹窗
const openEditModal = (parent) => {
    currentlyNode.value = parent;
    isEditing.value = true;
    categoryName.value = parent.name;
    showModal.value = true;
};

// 关闭弹窗
const closeModal = () => {
    showModal.value = false;
    error.value="";
};

// 保存分类
const saveCategory = async () => {
  // 验证输入
  if (!categoryName.value.trim()) {
      error.value = '分类名称不能为空';
      return;
  }

  if(!await judgeCategoryName()){
    return;
  }

  if (isEditing.value) {
      // 更新现有分类
      updateCategory();
  } else {
      // 添加新分类
    let childType = 1;
    let parentId1 = 0;
    if(currentlyNode.value != null){
      // 根据父节点type确定子节点级别
      childType = currentlyNode.value.type + 1;
      parentId1 = currentlyNode.value.id;
    }

  // 最多只能到3级
  if (childType > 3) return;
  
  const newChild = {
    name: categoryName.value,
    parentId: parentId1,
    type: childType,
    iconClass: "",
    isdel: 0,
    expanded: false,
    children: []
  };

  console.log(newChild);
    // 添加子分类
    addCategory(newChild);
      
  }
  // 关闭弹窗
  closeModal();
};

//添加子分类
const addCategory = async (newChild) =>{
  try{
      const response = await axios.post('/api/addCategory',{
          name:newChild.name,
          parentId:newChild.parentId,
          type:newChild.type
      })

      if(response.data.code==5500){
        alert("添加失败！");
        return;
      }
      alert("添加成功！");
      newChild.id = response.data.id;
      console.log(newChild);
      
      
      if(newChild.parentId==0){
        treeData.value.push(newChild);
      }else{
        currentlyNode.value.children.push(newChild);
      }
  }catch(error){
      alert('不可重名！');
  }
}

//修改当前分类
const updateCategory = async () =>{
  try{
      const response = await axios.post('/api/updateCategory',{
          id:currentlyNode.value.id,
          name:categoryName.value,
      })
      alert("修改成功！");
      currentlyNode.value.name=categoryName.value
  }catch(error){
      alert('修改失败！');
  }
}

// 切换一级分类展开/折叠（手风琴效果）
const toggleFirstLevel = (index) => {
  // 关闭所有一级分类
  treeData.value.forEach(item => {
    item.expanded = false;
  });
  // 打开当前点击的一级分类
  treeData.value[index].expanded = true;
};

// 切换二级分类展开/折叠
const toggleSecondLevel = (parent, index) => {
  parent.children[index].expanded = !parent.children[index].expanded;
};



// 删除节点
const deleteNode = async (parentNode, index) => {
  if(!confirm('确定要删除吗？')){
    return;
  }
let id = 0;
let type = 0;
console.log(treeData.value);
console.log(parentNode);
console.log(index);

if(parentNode==null){//删除一级分类  
  id=treeData.value[index].id;
  type=treeData.value[index].type;
}else{
  id=parentNode.children[index].id;
  type=parentNode.children[index].type;
}
console.log(id);
console.log(type);

  try{
      const response = await axios.post('/api/deleteCategory',{
          id:id,
          type:type
      })

      if(response.data.code === 5200){
          alert("删除成功！");
          if (parentNode === null) {
          // 删除一级分类
          treeData.value.splice(index, 1);
          } else {
          // 删除子分类
          parentNode.children.splice(index, 1);
          }
      }else{
          alert('不可删除！请先删除子分类或是该分类下的商品');

      }
  }catch(error){
      alert('不可删除');
  }
};
//判断重名
const judgeCategoryName = async ()=>{
  let type = 1;
  if(currentlyNode.value!=null){
    type = currentlyNode.value.type + 1
  }
  if(categoryName.value.trim()==null || categoryName.value.trim()==''){
    error.value="请输入分类名"
    return;
  }

  try{ 
    const res = await axios.post('/api/judgeCategoryName',{
      name: categoryName.value.trim(),
      type: type
    })
    
    if(res.data.code==5500){
      error.value="请勿重复添加！"
      return false;
    }
    error.value="";
    return true;
  }catch(error){
      alert('请勿重复添加！');
  }
}

</script>

<style scoped>
.close-button {
    background: none;
    border: none;
    font-size: 1.5rem;
    color: #7f8c8d;
    cursor: pointer;
}

.form-group {
    margin-bottom: 20px;
}

label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    color: #34495e;
}

input {
    width: 100%;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
    font-size: 1rem;
}

input:focus {
    outline: none;
    border-color: #3498db;
}

.modal-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.save-btn {
    background: #3498db;
    color: white;
}

.save-btn:hover {
    background: #2980b9;
}

.cancel-btn {
    background: #95a5a6;
    color: white;
}

.cancel-btn:hover {
    background: #7f8c8d;
}

.error {
    color: #e74c3c;
    font-size: 0.85rem;
    margin-top: 5px;
}
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.modal {
    background: white;
    border-radius: 10px;
    width: 90%;
    max-width: 400px;
    padding: 25px;
    box-shadow: 0 5px 20px rgba(0, 0, 0, 0.2);
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
}

.modal-title {
    font-size: 1.3rem;
    color: #2c3e50;
}
.tree-wrapper {
  max-width: 800px;
  margin: 20px 80px; /* 与标题对齐 */
  padding: 15px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
}

/* 加载和空状态样式 */
.loading, .empty {
  padding: 20px;
  text-align: center;
  color: #666;
}

.category-tree {
  list-style: none;
  padding: 0;
  margin: 0;
}

.tree-item {
  margin: 5px 0;
}

.tree-item-content {
  display: flex;
  align-items: center;
  padding: 6px 0;
}

.toggle-icon {
  width: 20px;
  height: 20px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  transition: transform 0.2s;
}

.category-name {
  flex: 1;
  padding: 4px 8px;
  cursor: pointer;
  border-radius: 3px;
  transition: background-color 0.2s;
}

.category-name:hover {
  background-color: #f3f4f6;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.add-btn, .delete-btn {
  padding: 3px 8px;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.2s;
}

.add-btn {
  background-color: #10b981;
  color: white;
}

.add-btn:disabled {
  background-color: #a7f3d0;
  cursor: not-allowed;
}

.delete-btn {
  background-color: #ef4444;
  color: white;
}

.add-btn:hover:not(:disabled), .delete-btn:hover {
  opacity: 0.9;
  transform: translateY(-1px);
}

.add-btn:active:not(:disabled), .delete-btn:active {
  transform: translateY(0);
}

/* 层级缩进 */
.level-2 {
  padding-left: 20px;
  border-left: 1px dashed #ddd;
  margin-left: 10px;
}

.level-3 {
  padding-left: 20px;
  border-left: 1px dashed #ddd;
  margin-left: 10px;
}
</style>
